package com.umbacos.udm.client.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class Files extends ArrayList<File>{

	private static final long serialVersionUID = -6496892944207227014L;
	
	public int selected=-1;
	public boolean isMultiSelection=false;
	
	public void select(int i) {
		if (isMultiSelection)
			get(i).selected = true;
		else
			selected = i;
	}

	public void unselect(int i) {
		if (isMultiSelection)
			get(i).selected = false;
		else
			selected = -1;
	}

	public void toggleSelection(int i) {
		if (isMultiSelection)
			get(i).selected = !get(i).selected;
		else
			selected = (selected==-1?i:-1);
	}

	public boolean add(File f){
		super.add(f);
		return true;
	}
	
	public boolean remove(File f){
		super.remove(f);
		return true;
	}
	
	public File remove(int i){
		return super.remove(i);
	}
	
	public void clear() {
		super.clear();
	}
	
	public static enum SortOrder {NAME, DATE, SIZE}

	private int ascDesc = 1;
	public SortOrder currentSort = SortOrder.NAME;
	public void setSortAsc(){ ascDesc=1; }
	public void setSortDesc(){ ascDesc=-1; }
	public void toggleSort(){ ascDesc=-ascDesc; }
	public boolean isSortAsc(){ return ascDesc==1; }
	
	public void sortFiles(SortOrder sortOrder){
		currentSort = sortOrder;
		switch (sortOrder) {
		case NAME:
			Collections.sort(this, new CompareFilesByName());
			break;
			
		case DATE:
			Collections.sort(this, new CompareFilesByDate());
			break;
			
		case SIZE:
			Collections.sort(this, new CompareFilesBySize());
			break;		
		}
	}
	private class CompareFilesByName implements Comparator<File> {
		public int compare(File o1, File o2) {
			if (o1.type != o2.type)
				return o1.type == File.FileType.DIR ? -1 : 1;  
			return ascDesc*o1.file.compareToIgnoreCase(o2.file); 
		}
	}
	private class CompareFilesBySize implements Comparator<File> {
		public int compare(File o1, File o2) {
			if (o1.type != o2.type)
				return o1.type == File.FileType.DIR ? 1 : -1;
			return ascDesc * comvertToDouble(o1).compareTo(comvertToDouble(o2)); 
		}
	}
	private Double comvertToDouble(File i){
		String[] s = i.size.split(" ");
		Double o = new Double(s[0]);
		if (s.length > 1) {
			switch (s[1].charAt(0)){
			case 'K': o=o*1000; break;
			case 'M': o=o*1000000; break;
			case 'G': o=o*1000000000; break;
			}
		}
		return o;
	}
	private class CompareFilesByDate implements Comparator<File> {
		public int compare(File o1, File o2) {
			String o1Date = reFraseDate(o1.date);
			String o2Date = reFraseDate(o2.date);
			return ascDesc*o1Date.compareTo(o2Date); 
		}
	}

	private static String reFraseDate (String date) {
		String[] dd=date.split(" ");
		String[] d=dd[0].split("/");
		String[] h=dd[1].split(":");
		return d[2]+pad(d[1])+pad(d[0])+pad(h[0])+pad(h[1]);
	}
	private static String pad(String s) {
	    return ("0" + s).substring(s.length()-1);  
	}
}
